package club.menglinking.wechat.configuration;

import club.menglinking.wechat.entity.ExceptionEntity;
import club.menglinking.wechat.util.BaseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName ExceptionCatch
 * @Author wuxuan
 * @Date 2019/1/6 15:07
 * @Version 1.0
 * @Description 捕获全局异常
 **/
@ControllerAdvice
@Slf4j
public class ExceptionCatch {

    ObjectMapper mapper = new ObjectMapper();

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public String returnExceptionMsg(Exception e, HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        ExceptionEntity exception = new ExceptionEntity();
        exception.setMsg(e.toString());
        exception.setRequestURL(request.getRequestURI());
        exception.setStatus(500);
        exception.setTime(BaseUtil.getBaseUtil().getFormatTime());

        log.error("捕获到一个异常,"+BaseUtil.getBaseUtil().stringFormat(mapper.writeValueAsString(exception)));
        return mapper.writeValueAsString(exception);
    }


}



